package cn.bluemobi.dylan.step.moder.http;


import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cn.bluemobi.dylan.step.BuildConfig;
import cn.bluemobi.dylan.step.app.App;
import cn.bluemobi.dylan.step.app.Constants;
import cn.bluemobi.dylan.step.moder.http.api.GoodsApis;
import cn.bluemobi.dylan.step.moder.http.api.StepcountApis;
import cn.bluemobi.dylan.step.moder.http.api.UserApis;
import cn.bluemobi.dylan.step.moder.http.interceptor.HttpLogger;
import cn.bluemobi.dylan.step.utils.common.LogUtils;
import cn.bluemobi.dylan.step.utils.andro.NetworkUtils;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitHelper {

    private static OkHttpClient okHttpClient = null;
    private static UserApis loginApi;
    private static GoodsApis goodsApi;
    private static StepcountApis trainApi;

    public static UserApis getLoginApi() {
        initOkHttp();
        if (loginApi == null) {
            Retrofit retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(Constants.baseUrl_member)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            loginApi = retrofit.create(UserApis.class);
        }
        return loginApi;
    }

    public static GoodsApis getGoodsApi() {
        initOkHttp();
        if (goodsApi == null) {
//            Gson gson = new GsonBuilder()
//                    .setDateFormat("yyyy-MM-dd HH:mm:ss")
//                    .registerTypeAdapter(Date.class,new TimestampTypeAdapter()).setDateFormat(DateFormat.LONG)
//                    .create();
//            Gson gson = new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            Retrofit retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(Constants.baseUrl_goods)
                    .addConverterFactory(GsonConverterFactory.create())
//                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            goodsApi = retrofit.create(GoodsApis.class);
        }
        return goodsApi;
    }

    public static StepcountApis getStepcountApi() {
        initOkHttp();
        if (trainApi == null) {
            Retrofit retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(Constants.baseUrl_member)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            trainApi = retrofit.create(StepcountApis.class);
        }
        return trainApi;
    }

    private static void initOkHttp() {
        if (okHttpClient == null) {
            LogUtils.debug("11111111111111111","ppppppppppppppppppp=initOkHttp");

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            if (BuildConfig.DEBUG) {
//                HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
//                loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
//                builder.addInterceptor(loggingInterceptor);
//                LoggingInterceptor interceptor = new LoggingInterceptor();
//                LoggingInterceptor interceptor = new LoggingInterceptor();

//                HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
//                    @Override
//                    public void log(String message) {
//                        try {
//                            StringReader reader = new StringReader(message);
//                            Properties properties = new Properties();
//                            properties.load(reader);
//                            properties.list(System.out);
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                });
                HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
                logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                builder.addInterceptor(logInterceptor);
            }
//            builder.retryOnConnectionFailure(false);

//            builder.addInterceptor(new CommonParamInterceptor());

            String PATH_DATA = App.getInstance().getCacheDir().getAbsolutePath() + File.separator + "data";
            String PATH_CACHE = PATH_DATA + File.separator + "NetCache";

            File cacheFile = new File(PATH_CACHE);
            Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
            Interceptor cacheInterceptor = new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    if (!NetworkUtils.isNetworkConnected(App.getInstance())) {
                        request = request.newBuilder()
                                .cacheControl(CacheControl.FORCE_CACHE)
                                .build();
                    }
                    int tryCount = 0;
                    Response response = chain.proceed(request);
                    while (!response.isSuccessful() && tryCount < 3) {

//                        KL.d(RetrofitHelper.class, "interceptRequest is not successful - :{}", tryCount);

                        tryCount++;

                        // retry the request
                        response = chain.proceed(request);
                    }

                    if (NetworkUtils.isNetworkConnected(App.getInstance())) {
                        int maxAge = 0;
                        // 有网络时, 不缓存, 最大保存时长为0
                        response.newBuilder()
                                .header("Cache-Control", "public, max-age=" + maxAge)
                                .removeHeader("Pragma")
                                .build();
                    } else {
                        // 无网络时，设置超时为4周
                        int maxStale = 60 * 60 * 24 * 28;
                        response.newBuilder()
                                .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                                .removeHeader("Pragma")
                                .build();
                    }
                    return response;
                }
            };
            //设置缓存
//            builder.addNetworkInterceptor(cacheInterceptor);
            builder.addInterceptor(cacheInterceptor);
            builder.cache(cache);
            //设置超时
            builder.connectTimeout(10, TimeUnit.SECONDS);
            builder.readTimeout(20, TimeUnit.SECONDS);
            builder.writeTimeout(20, TimeUnit.SECONDS);
            //错误重连
            builder.retryOnConnectionFailure(true);
            okHttpClient = builder.build();
        }
    }
}
